require_dependency 'map_utils'

class TagsController < ApplicationController

  include MapUtils
  #alias for list
  def index
    list
    render :action => :list
  end
  
  def list
    tags = Array.new
    @tags_count = Array.new
    ecasetags = Ecase.find(:all,:select=>"id,tags")
    eventtags = Event.find(:all,:select=>"id,tags")
    joinedtags = ecasetags + eventtags
    joinedtags.each do |e|
      if !e[:tags].nil?  && (tag = e[:tags].strip).size > 0
        subtag = tag.split(',')
        subtag.each do |t|
           t = t.strip
           if (i = tags.index(t)).nil?
            tags.push(t)
            h = { "num" => 1, "tag" => t }
            @tags_count.push(h)
           else 
            @tags_count[i]["num"] += 1
           end
        end
      end
    end
    if @tags_count.size > 0 
      @tags_count = (@tags_count.sort_by {|h| h["num"]}.reverse)[0..100]
      @dmax = 40.0
      @dmin = 10.0
      @max = @tags_count[0]["num"].to_f
      @min = @tags_count[@tags_count.size-1]["num"].to_f
      @tags_count = @tags_count.sort_by {|h| h["tag"].downcase }
    end
    @ecases = Ecase.find(:all, :order => "title ASC")
    set_list_map
  end

  def show
    @results = Array.new
    @tag = (params[:tag] && !(p = params[:tag].strip).empty? ) ? p : ""
    if !@tag.empty?
      search_tag = "%"+@tag+"%"
      ecasetags = Ecase.find(:all,:select=>"id,title,date,tags",:conditions =>["tags LIKE ?",search_tag])
      eventtags = Event.find(:all,:select=>"id,title,date,tags",:conditions =>["tags LIKE ?",search_tag])
      joinedtags = ecasetags + eventtags
      joinedtags.each do |e|
        subtag = (e[:tags].strip).split(',')
        subtag.each do |t|
           if t.strip == @tag
              @results.push(e)
              break
           end
        end
      end
    end
    @map = get_map("gmap") 
  end
 
  
end
